package com.decade.sp11.filter;

import com.decade.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: decade
 * @Description: 访问过滤器
 * @Date: 2021/1/21 14:31
 **/
@Component
public class AccessFilter extends ZuulFilter {
    //指定过滤器的类型，前置过滤器"pre",中间："routes",后置："post",错误："error"
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //定制过滤器添加的位置序号
    @Override
    public int filterOrder() {
        //已经有5个默认的过滤器
        //在第五个过滤器中放入serviceId属性，所以在第五个之后获取serviceId
        return 6;
    }
    //判断针对当前这次请求，是否要执行过滤代码
    //如果请求item-service，执行全选判断
    //如果请求user或者order，直接跳过过滤代码
    @Override
    public boolean shouldFilter() {
        //对指定的serviceid过滤，如果要过滤所有服务，直接返回 true
        //获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        if("item-service".equalsIgnoreCase(serviceId)){
            return true;
        }
        return false;
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest req = ctx.getRequest();
        String token = req.getParameter("token");
        if (StringUtils.isBlank(token)){
            //此设置会阻止请求被路由到后台微服务
            ctx.setSendZuulResponse(false);
            //向客户端的响应
//            ctx.setResponseStatusCode(200);
            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(JsonResult.err().code(JsonResult.NOT_LOGIN).msg("没有登录").toString());
        }
        return null;//返回任何数据都无效
    }
}
